package com.linb.pan.storage.engine.fastdfs;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.linb.pan.core.constants.BPanConstants;
import com.linb.pan.core.exception.BPanBusinessException;
import com.linb.pan.core.utils.FileUtil;
import com.linb.pan.storage.engine.core.AbstractStorageEngine;
import com.linb.pan.storage.engine.core.context.*;
import com.linb.pan.storage.engine.fastdfs.config.FastDFSStorageEngineConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

@Component
@Slf4j
public class FastDFSStorageEngine extends AbstractStorageEngine {

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FastDFSStorageEngineConfig config;

    /**
     * 读取文件内容并写入到输出流中
     */
    @Override
    protected void doReadFile(ReadFileContext context) throws IOException {
        String realPath = context.getRealPath();
        String group = realPath.substring(0, realPath.indexOf(BPanConstants.SLASH_STR));
        String path = realPath.substring(realPath.indexOf(BPanConstants.SLASH_STR) + 1);
        DownloadByteArray downloadByteArray = new DownloadByteArray();
        log.info("group:{},path:{}", group, path);
        byte[] bytes = client.downloadFile(group, path, downloadByteArray);
        OutputStream outputStream = context.getOutputStream();
        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();
    }

    /**
     * 执行文件分片动作 下沉处理
     */
    @Override
    protected void doMergeFile(MergeFileContext context) throws IOException {
        throw new BPanBusinessException("fdfs暂不支持分片");

    }

    /**
     * 执行保存文件分片
     */
    @Override
    protected void doStoreChunk(StoreFileChunkContext context) throws IOException {
        throw new BPanBusinessException("fdfs暂不支持分片");
    }

    /**
     * 交给具体的存储引擎类进行存储处理
     */
    @Override
    protected void doStore(StoreFileContext context) throws IOException {
        StorePath storePath = client.uploadFile(config.getGroup(), context.getInputStream(),
                context.getTotalSize(), FileUtil.getFileExtName(context.getFilename()));
        context.setRealPath(storePath.getFullPath());
    }

    /**
     * 交给具体的存储引擎类进行批量删除文件
     */
    @Override
    protected void doDelete(DeleteFileContext context) {
        List<String> realFilePathList = context.getRealFilePathList();
        if (CollectionUtils.isNotEmpty(realFilePathList)) {
            //调用fdfs的Api删除
            realFilePathList.stream().forEach(client::deleteFile);
        }
    }
}
